package com.ocean.linkedlist;

/**
 * https://leetcode.cn/problems/linked-list-cycle-ii/
 */
public class LinkedListCycleDetect2 {
    public static void main(String[] args) {

        ListNode e5 = new ListNode(5, null);
        ListNode e4 = new ListNode(4, e5);
        ListNode e3 = new ListNode(3, e4);
        ListNode e2 = new ListNode(2, e3);
        ListNode e1 = new ListNode(1, e2);
        e5.next = e2;
        ListNode listNode = new LinkedListCycleDetect2().detectCycle(e1);
        System.out.println(listNode);
    }


    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null) {
            ListNode next = fast.next;
            if (next == null) {
                return null;
            }
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                break;
            }
        }

        ListNode temp = head;

        while (temp != slow) {
            temp = temp.next;
            slow = slow.next;
        }
        return temp;
    }
}
